/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.util.bdfparser.validation;

import cn.hutool.core.collection.CollectionUtil;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.isfd.util.bdfparser.entities.bdf.cards.BaseCard;
import com.comac.ins.isfd.util.bdfparser.entities.bdf.cards.Comment;
import com.comac.ins.isfd.util.bdfparser.entities.bdf.rawdata.RawDataLine;
import com.comac.ins.isfd.util.bdfparser.entities.bdf.sections.BulkDataEntry;
import com.comac.ins.isfd.util.bdfparser.enums.cardeums.CardNameEnums;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * 卡片格式验证一些方法类
 */
@Slf4j
public class CardValidationUtils {

    /**
     * 检查验证卡片有效性, 并生成fields
     */
    public static boolean isValidCard(BaseCard card) {
        // 验证是否为支持的卡片
        if (!CardNameEnums.isSupportedCard(card.getName())) {
            log.warn("不支持该类型卡片({})", card.getName());
            return false;
        }
        // 生成fields
        return parseCardFields(card);
    }

    /**
     * 解析卡片数据段
     */
    private static boolean parseCardFields(BaseCard card) {
        try {
            List<List<String>> cardFields = new ArrayList<>();

            // todo: 特殊处理HyperMesh卡片
            if (card.getName().contains("HW") || card.getName().contains("HM")) {
                return false;
            }

            for (RawDataLine rawDataLine : card.getRawDataLines()) {
                String line = rawDataLine.getLine();
                line = expandTabs(line); // 展开tabs
                line = line.stripTrailing(); // 去掉尾部空格

                // 校验字符串长度 > 80 无效
                if (line.length() > 80) {
                    log.warn("跳过当前卡片, 字符串长度 > 80， card：{}{}, file:{},, row: {}, line: {}", card.getName(), card.getId(), rawDataLine.getRelativePath(), rawDataLine.getRowNumber(), line);
                    return false;
                }
                List<String> lineFields = new ArrayList<>();
                int fieldLengthLimit = 8; int fieldCountLimit = 10;
                // 检查field format，设置解析方法
                String firstField = line.substring(0, Math.min(8, line.length())) // 截取前8个字符，防止越界
                    .split(",", 2)[0];   // 按逗号分割，取第一部分
                if (firstField.contains("*")) {
                    fieldLengthLimit = 16; fieldCountLimit = 6; // large field format
                }
                lineFields.add(firstField);
                // 按照field format划分
                if (line.contains(",")) {
                    String[] fields = line.split(",");
                    lineFields.addAll(Arrays.asList(fields).subList(1, Math.min(fieldLengthLimit, fields.length)));
                } else {
                    line = String.format("%-80s", line);
                    for (int i = 1; i < fieldCountLimit; i++){
                        String field = line.substring(8 + (i-1)*fieldLengthLimit, Math.min(8+i*fieldLengthLimit, line.length()));
                        lineFields.add(field);
                    }
                }
                cardFields.add(lineFields);
            }
            card.setFields(cardFields);
            if (!isValidFields(card)) {
                log.warn("卡片属性字段不符合规则, card: {}", card);
                return false;
            }
            card.setId(Integer.parseInt(cardFields.get(0).get(1).strip()));
            // 去掉没有id的卡片
            if (card.getId() == null) {
                log.warn("未解析出卡片id, card: {}", card);
                return false;
            }
            return true;
        } catch (Exception e) {
            log.warn("解析卡片失败，card：{}{} , error:{}", card.getName(), card.getId(), e.getMessage());
            return false;
        }
    }

    /**
     * todo：检查field格式是否符合要求
     */
    private static boolean isValidFields(BaseCard card) {
        List<List<String>> cardFields = card.getFields();
        return true;
    }

    /**
     * 展开制表符
     */
    private static String expandTabs(String input) {
        if (input == null) {
            return input;
        }
        // 将 \t 替换为固定数量的空格
        String spaces = " ".repeat(8);
        return input.replace("\t", spaces);
    }

}
